package com.dj.mingkong.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class ApiPlatAuthUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(ApiPlatAuthUtils.class);

    public ApiPlatAuthUtils() {
    }

    private static String jwtAuthorizationToken(String appKey, String appSecret) {
        Algorithm algorithm = Algorithm.HMAC256(appSecret);
        Map<String, Object> headerClaims = new HashMap();
        headerClaims.put("alg", "HS256");
        headerClaims.put("typ", "JWT");
        Map<String, Object> payloadClaims = new HashMap();
        payloadClaims.put("iss", appKey);
        String token = JWT.create().withHeader(headerClaims).withPayload(payloadClaims).sign(algorithm);
        return token;
    }

    public static String sign(String appKey, String appSecret) {
        if (!StringUtils.isEmpty(appKey) && !StringUtils.isEmpty(appSecret)) {
            String token = jwtAuthorizationToken(appKey, appSecret);
            StringBuilder builder = new StringBuilder();
            builder.append("Bearer ");
            builder.append(token);
            return builder.toString();
        } else {
            LOGGER.warn("api服务市场签名认证参数配置错误，请检查配置,appKey:[coli.openapi.platform.appKey] ,appSecret:[coli.openapi.platform.appSecret]");
            return "";
        }
    }
}
